<?php

/**
 *
 */
Class Lib_CallCenter_YunKeFu_Curl
{

    public static $json_header = array('Content-Type:application/json;charset=utf-8');

    public static function postjson($url, $params = [], $header =[], $timeout = 60)
    {
        $logs = ' ssid='.$params['ssid'];
        unset($params['ssid']);
        $logs .= ' request_url='.$url;
        $params = json_encode($params);
        $logs .= ' request_params='.$params;

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_NOBODY, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array_merge(self::$json_header,$header));
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        $res = curl_exec($ch);
        $log['errno'] = curl_errno($ch);
        $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
        $log['httpcode'] = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        if ($log['errno'] !== 0) {
            curl_close($ch);
            $result['errno'] = $log['errno'];
            return $result;
        }
        curl_close($ch);
        $logs .= ' response : '.substr($res, $header_size);
        $res = json_decode(substr($res, $header_size), true);
        if (!is_array($res) || count($res) <= 0) {
            //返回值错误日志
            $log['errno'] = 401;
            $log['message'] = 'Inlegal json response';
            Func_Log::write('callCenter_curl_YunKeFu_postjson', 'curl_response401', $logs.json_encode($log));
            $result['errno'] = $log['errno'];
            return $result;
        }
        if(isset($res['code'])){
            if($res['code'] != 200){
                //返回值错误日志
                $log['errno'] = $res['code'];
                $log['message'] = $result['message'] = $res['message'] ;
                Func_Log::write('callCenter_curl_YunKeFu_postjson', 'curl_response401', $logs.json_encode($log));
                $result['errno'] = $log['errno'];
                return $result;
            }
        }
        Func_Log::write('callCenter_curl_YunKeFu_postjson', 'curl_response401', $logs.json_encode($res));

        if(((isset($res['Succeed']) && !$res['Succeed']) || isset($res['Message'])) || (isset($res['success']) && !$res['success'])){
            if(isset($res['Reason'])){
                //签入签出特殊
                $res['code'] =  $res['Reason'];
                $res['Message'] = "error";
            }else{
                $code = intval(substr($res['Message'],0,4));
                $res['code'] = empty($code) ? 4000 : $code;
                $res['Message'] = '这个坐席未注册sip号或者未绑定sip号';
            }
            $log['errno'] = $res['code'];
            $log['message'] = $res['Message'];
            $result['errno'] = $res['code'];
            $result['message'] = $res['Message'];
            Func_Log::write('callCenter_curl_YunKeFu_postjson', 'curl_response401', $logs.json_encode($log));
            return $result;
        }
        Func_Log::write('callCenter_curl_YunKeFu_postjson',   'curl_end', $logs);
        $res['errno'] = 200;
        return $res;
    }
    /**
     * @param $url
     * @param $params
     * @return mixed
     * get请求
     */
    public static function get($url, $params = [], $timeout = 20)
    {
        $logs = ' ssid='.$params['ssid'];
        unset($params['ssid']);
        $url = strstr($url, '?') ? $url . '&' . urldecode(http_build_query($params)) : $url . '?' . urldecode(http_build_query($params));
        $logs .= ' request_url='.$url;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);


        $res = curl_exec($ch);
        $log['errno'] = curl_errno($ch);
        $log['httpcode'] = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        if ($log['errno'] !== 0) {
            curl_close($ch);
            $result['errno'] = $log['errno'];
            return $result;
        }
        curl_close($ch);
        $res = json_decode($res, true);
        if (!is_array($res) || count($res) <= 0) {
            //返回值错误日志
            $log['errno'] = 401;
            $log['message'] = 'Inlegal json response';
            Func_Log::write('callCenter_curl_get', 'curl_response401', $logs.json_encode($log));
            $result['errno'] = $log['errno'];
            return $result;
        }
        Func_Log::write('callCenter_curl_get',   'curl_end', $logs);
        $res['errno'] = 200;
        return $res;
    }

    public static function putjson($url, $params = [])
    {
        $ch = curl_init(); //初始化CURL句柄
        curl_setopt($ch, CURLOPT_URL, $url); //设置请求的URL
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //设为TRUE把curl_exec()结果转化为字串，而不是直接输出
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));//设置提交的字符串
        curl_setopt($ch, CURLOPT_HTTPHEADER, self::$json_header);//设置头部json格式
        $res = curl_exec($ch);
        curl_close($ch);
        return $res;
    }

    /*
     * send multi http request by curl
     * @param data array every element include an 'url' and a 'post' key will do post requst
     * @param opertions array() custom curl opertions
     * */
    public static function multiRequest($data, $options = array(), $format = 'json', $return_header = false, $timeout = 5)
    {
        // array of curl handles
        $curly = array();
        $infos = array();
        // data to be returned
        $result = array();

        // multi handle
        $mh = curl_multi_init();

        // loop through $data and create curl handles
        // then add them to the multi-handle
        TyqFunc_Log::write('multiRequest', 'start', '=====================================================');
        foreach ($data as $id => $d) {

            $curly[$id] = curl_init();

            $url = (is_array($d) && !empty($d['url'])) ? $d['url'] : $d;
            curl_setopt($curly[$id], CURLOPT_URL, $url);
            curl_setopt($curly[$id], CURLOPT_HEADER, 0);
            curl_setopt($curly[$id], CURLOPT_RETURNTRANSFER, 1);
            // post?
            if (is_array($d)) {
                if (!empty($d['post'])) {
                    curl_setopt($curly[$id], CURLOPT_HEADER, true);
                    curl_setopt($curly[$id], CURLOPT_NOBODY, true);
                    curl_setopt($curly[$id], CURLOPT_POST, true);
                    if ($format == 'json') {
                        curl_setopt($curly[$id], CURLOPT_HTTPHEADER, self::$json_header);
                        $d['post'] = json_encode($d['post']);
                    }
                    //log request data
                    TyqFunc_Log::write('multiRequest', 'request', is_array($d['post']) ? json_encode($d['post']) : $d['post']);
                    curl_setopt($curly[$id], CURLOPT_TIMEOUT, $timeout);
                    curl_setopt($curly[$id], CURLOPT_POSTFIELDS, $d['post']);
                }
            }

            // extra options?
            if (!empty($options)) {
                curl_setopt_array($curly[$id], $options);
            }

            curl_multi_add_handle($mh, $curly[$id]);
        }

        // execute the handles
        $active = null;
        do {
            $mrc = curl_multi_exec($mh, $active);
        } while ($mrc == CURLM_CALL_MULTI_PERFORM);

        while ($active && $mrc == CURLM_OK) {
            // add this line
            while (curl_multi_exec($mh, $active) === CURLM_CALL_MULTI_PERFORM) ;

            if (curl_multi_select($mh) != -1) {
                do {
                    $mrc = curl_multi_exec($mh, $active);
                    if ($mrc == CURLM_OK) {
                        while ($info = curl_multi_info_read($mh)) {
                            TyqFunc_Log::write('multiRequest', 'info', $info['result']);
                        }
                    }
                } while ($mrc == CURLM_CALL_MULTI_PERFORM);
            }
        }


        // get content and remove handles
        foreach ($curly as $id => $c) {
            $response = curl_multi_getcontent($c);
            TyqFunc_Log::write('multiRequest', 'response', $response);
            if (!$return_header) {
                $header_size = curl_getinfo($c, CURLINFO_HEADER_SIZE);
//                $result[$id]['header'] = trim(substr($response,0,$header_size));
                $result[$id]['code'] = curl_getinfo($c, CURLINFO_HTTP_CODE);
                $result[$id]['body'] = substr($response, $header_size);
            }
            curl_multi_remove_handle($mh, $c);
        }

        // all done
        curl_multi_close($mh);
        TyqFunc_Log::write('multiRequest', 'end', '=====================================================');
        return $result;
    }
}